<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="rule-form">
        <el-form-item label="设备所属部门" prop="equipmentAccountDictionaryId">
          <el-cascader style="width:100%" v-model="ruleForm.equipmentAccountDictionaryId" :options="DeptList"
            placeholder="请选择所属部门"
            :props="{ expandTrigger: 'hover', label: 'deptName', value: 'deptId', checkStrictly: true }"
            @change="handleChange">
          </el-cascader>
        </el-form-item>

        <el-form-item label="设备名称" prop="equipmentAccountId">
          <el-select v-model="ruleForm.equipmentAccountId" filterable placeholder="请选择设备">
            <el-option v-for="item in equipmentAccountList" :key="item.equipmentAccountId"
              :label="item.equipmentName + '(' + item.equipmentNum + ')'" :value="item.equipmentAccountId" />
          </el-select>
        </el-form-item>

        <el-form-item label="故障等级" prop="faultLevel">
          <el-select v-model="ruleForm.faultLevel" filterable placeholder="请选择设备">
            <el-option v-for="(item, i) in ['紧急', '严重', '一般']" :key="i" :label="item" :value="i" />
          </el-select>
        </el-form-item>

        <el-form-item label="故障类型" prop="faultType">
          <el-select v-model="ruleForm.faultType" multiple placeholder="请选择故障类型">
            <el-option v-for="item in DictionaryList" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="故障描述" prop="faultDescribe">
          <el-input type="textarea" placeholder="请输入描述" v-model="ruleForm.faultDescribe" maxlength="100"
            show-word-limit />
        </el-form-item>

        <el-divider>附件：异常图片/异常视频</el-divider>

        <el-form-item label="异常图片">
          <Image-upload :value='ruleForm.repairImages' @input="handleInput" />
        </el-form-item>

        <el-form-item label="异常视频">
          <Video-upload ref="videoUpload" v-model="ruleForm.faultVideo" @returnBack="handleReturnBack" />
        </el-form-item>

        <el-divider>审核信息</el-divider>
        <el-form-item label="委外服务商" prop="supplierId">
          <el-select v-model="ruleForm.supplierId" placeholder="请选择处理结果" @change="handleSelectSupplier">
            <el-option v-for="item in supplierList" :key="item.supplierId" :label="item.supplierName"
              :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input disabled v-model="ruleForm.supplierTitle" />
        </el-form-item>

        <el-form-item label="审核人" prop="auditVosUser">
          <el-select v-model="ruleForm.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="">
          <span v-for="(tag, index) in tagUserList" :key="index">
            <el-tag closable disable-transitions @close="tagChange(tag, index)">
              <span>{{ tag.name }}</span>
            </el-tag>
            <span style="font-size:28px;position: relative;top: 5px;">
              <template v-if="index !== tagUserList.length - 1">
                <i class="el-icon-caret-right"></i>
              </template>
            </span>
          </span>

        </el-form-item>
        <el-form-item label="抄送人">
          <el-select v-model="ruleForm.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div align="center" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <!-- <el-button  @click="handleReset">重置</el-button> -->
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { listEquipmentAccount, listDictionary, add, listDept, supplierlist, getuserlist, listDetail } from '@/api/maintenance/management/Outsourcing.js'
/** ------------------------------------------------------------------------------------------------------------------------------- */

/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  supplierTitle: '',
  equipmentAccountDictionaryId: null, // 部门id，只做下一步操作，不做表单数据
  equipmentAccountId: null, //设备ID
  faultLevel: null,//故障等级
  faultType: [], //故障类型
  faultDescribe: "", //故障描述
  repairImages: [], //图片集合
  faultVideo: "", //视频
  supplierId: '',// 委外服务商id
  auditVosUser: [],//审核人集合
  auditVosType: [],//抄送人集合
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */
// 新增维修工单处理函数-----------------------------
function processRuleForm (ruleForm) {
  const data = Object.assign({}, ruleForm)
  delete data.supplierTitle
  delete data.equipmentAccountDictionaryId
  const images = ruleForm.repairImages.map(item => {
    return {
      image: item.url,
      type: "0"
    }
  })
  const str = ruleForm.faultType.join(',')
  const auditVosArr1 = data.auditVosUser.map(item => {
    return {
      userId: item,
      userType: '0'
    }
  })
  const auditVosArr2 = data.auditVosType.map(item => {
    return {
      userId: item,
      userType: '1'
    }
  })
  const rule = {
    repairVo: {
      equipmentAccountId: data.equipmentAccountId,
      faultLevel: data.faultLevel,
      faultType: str,
      faultDescribe: data.faultDescribe,
      repairImages: images,
      faultVideo: data.faultVideo
    },
    supplierId: data.supplierId,
    auditVos: [...auditVosArr1, ...auditVosArr2]
  }
  return rule
}
// 分派处理函数---------------------------------------
function processRulefp (ruleForm) {
  console.log(ruleForm);
  let newArr1 = []
  let newArr2 = []
  newArr1.push({
    repairerId: ruleForm.repairers,
    type: 0
  })
  if (ruleForm.repairersArr.length) {
    newArr2 = ruleForm.repairersArr.map(item => {
      return {
        repairerId: item,
        type: 1
      }
    })
  }
  const newArr = [...newArr1, ...newArr2]
  const data = {
    repairId: ruleForm.repairId,
    repairers: newArr
  }
  return data
}

export default {
  name: 'Form',
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      isUpdateForm: false,
      dialogTitle: '',
      DeptList: [], // 部门数组
      DictionaryList: [], // 故障类型数组
      equipmentAccountList: [],//设备名称接收数组
      supplierList: [],//委外服务商数组
      allUserData: [],//审核人 和 抄送人 数组集合
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        equipmentAccountDictionaryId: [
          { required: true, message: '请选择部门', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        equipmentAccountId: [
          { required: true, message: '请选择设备', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultLevel: [
          { required: true, message: '请选择故障等级', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultDescribe: [
          { required: true, message: '请输入故障描述', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        repairImages: [
          { required: true, message: '请上传故障图片', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        faultType: [
          { required: true, message: '请选择故障类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        supplierId: [
          { required: true, message: '请选择委外服务商', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        auditVosUser: [
          { required: true, message: '请选择审核人', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        auditVosType: [
          { required: true, message: '请选择抄送人', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  computed: {
    // 审核人数据转换--------------------------
    tagUserList () {
      let Arr = []
      this.ruleForm.auditVosUser.map(item => {
        this.allUserData.map(value => {
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },
  created () {
    this.handleListType()
  },
  methods: {
    // 委外服务商选择事件-----------------------------------------
    handleSelectSupplier (id) {
      const rule = this.supplierList.filter(item => item.supplierId == id).map(item => item.liaison + '（' + item.phone + '）').join()
      this.ruleForm.supplierTitle = rule
    },
    // 设备所属部门选择事件---------------------------------
    handleChange (arr) {
      this.ruleForm.equipmentAccountId = null
      const id = arr.slice(-1).join()
      listEquipmentAccount({ 'params[userStatuses]': '0,1,2,4', 'params[statuses]': '0,3', 'params[deptIds]': id }).then(({ data: res }) => {
        this.equipmentAccountList = res
      })//设备名称
    },
    // 设备所属部门和设备名称 数据接口---------------------------------------------
    async handleListType () {
      const { data: res1 } = await listDept({ status: 0 })//部门列表
      const { data: res2 } = await listDictionary({ dictType: 'fault_type', status: 0 })//故障类型，字典单位
      const { data: res3 } = await supplierlist()
      const { data: res4 } = await getuserlist();
      this.DeptList = this.handleTree(res1, 'deptId')
      this.DictionaryList = res2
      this.supplierList = res3
      this.allUserData = res4
    },
    // 上传图片处理方法-----------------
    handleInput (val) {
      this.ruleForm.repairImages = val
    },
    // 上传视频处理方法--------------------
    handleReturnBack (val) {
      this.ruleForm.faultVideo = val
    },
    // 打开表单对话框
    openDialog (id) {
      if (id) {
        this.isUpdateForm = true;
        this.dialogTitle = '重新申请委外工单';
        listDetail(id).then(({ data: res }) => {
          // 设备所属部门数据回显--------
          const ruleId = this.getParentIdList(this.DeptList, res.repairVo.repairEquipmentAccountVo.eaPartInfoVo.deptId, { id: 'deptId' })
          this.ruleForm.equipmentAccountDictionaryId = ruleId;
          // 设备名称数据回显--------
          this.handleChange(ruleId);
          this.ruleForm.equipmentAccountId = res.repairVo.equipmentAccountId;
          // 故障等级数据回显----------
          this.ruleForm.faultLevel = res.repairVo.faultLevel * 1 || null;
          // 故障类型数据回显---------
          this.ruleForm.faultType = [...res.repairVo.faultType] || [];
          // 故障描述数据回显---------
          this.ruleForm.faultDescribe = res.repairVo.faultDescribe || '';
          // 故障描述数据回显---------
          this.ruleForm.repairImages = res.repairVo.repairImages.filter(item => item.type == 0).map(item => item.image) || [];
          // 故障视频数据回显---------
          this.ruleForm.faultVideo = res.repairVo.faultVideo || '';
          // 委外服务商数据回显---------
          this.ruleForm.supplierId = res.supplierId || '';
          // 联系人数据回显---------
          this.handleSelectSupplier(res.supplierId * 1);
          this.dialogVisible = true

        })
      } else {
        this.isUpdateForm = false;
        this.dialogTitle = '添加委外工单';
        this.dialogVisible = true
      }
    },
    // 审核人删除事件
    tagChange (val, index) {
      this.ruleForm.auditVosUser.splice(index, 1)
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.repairImages.length || this.ruleForm.faultVideo) {
            const data = processRuleForm(this.ruleForm)
            add(data).then(() => {
              this.$message({
                message: this.isUpdateForm ? '重新申请委外工单成功！' : '添加委外工单成功！',
                type: 'success'
              })
              this.resetForm('ruleForm')
              this.$nextTick(function () {
                this.$refs['ruleForm'].clearValidate()
              });
              this.dialogVisible = false
              this.$emit('submit_success')
            })
          } else {
            this.$message({
              message: '请上传异常图片或者异常视频！',
              type: 'error'
            })
          }

        } else {
          this.$message({
            message: '数据验证不通过，检查输入表单',
            type: 'error'
          })
          return false
        }
      })
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      this.ruleForm = Object.assign({}, ruleForm)
      this.$nextTick(function () {
        this.$refs['ruleForm'].clearValidate()
      });
      this.$refs.videoUpload.clearVideo() //删除视频
      this.dialogVisible = false
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
    resetForm () {
      this.handleClose()
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  width: 500px;
  margin-left: auto;
  margin-right: auto;

  .inventory {
    display: flex;
  }
}

::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}
</style>
